/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedLineData,
  pickedFaceData,
  pickedVertexData,
  pickedModelData,
} from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useState, useMemo, useEffect } from 'react';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { ChildSurfaceCommandProps } from './type';

type SplineType = {
  id: string;
  leftBound: string;
  rightBound: string;
};

type TwoPointsType = {
  type: string;
  point: string;
  pntDir: string;
};

type pointDirectType = {
  type: string;
  point: string;
  pntDir: string;
};

type Params = {
  mode: string;
  profile: string;
  guide1: string;
  guide2: string;
  position?: TwoPointsType | pointDirectType;
  spline?: SplineType;
  solution: number;
};

type FormData = {
  profile: pickedLineData | pickedModelData;
  guide1: pickedLineData;
  guide2: pickedLineData;
  type: string;
  point: pickedVertexData;
  pntDir: pickedLineData | pickedFaceData | pickedVertexData;
  splineId: pickedLineData;
  leftBound: pickedVertexData;
  rightBound: pickedVertexData;
};

export function Explicit({
  onClose,
  props,
  editDxid,
}: ChildSurfaceCommandProps) {
  const initData: FormData = {
    profile: null,
    guide1: null,
    guide2: null,
    type: 'twoPoints',
    point: null,
    pntDir: null,
    splineId: null,
    leftBound: null,
    rightBound: null,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const {
      profile,
      guide1,
      guide2,
      type,
      point,
      pntDir,
      splineId,
      leftBound,
      rightBound,
    } = formData;

    const params: Params = {
      mode: 'TwoGuideCurves',
      profile: getIdOfPickedObj(profile),
      guide1: guide1.edgeId,
      guide2: guide2.edgeId,
      position: {
        type: type,
        point: getIdOfPickedObj(point),
        pntDir: getIdOfPickedObj(pntDir),
      },
      spline: {
        id: splineId?.edgeId ?? guide1.edgeId,
        leftBound: leftBound ? leftBound.vertexId : undefined,
        rightBound: rightBound ? rightBound.vertexId : undefined,
      },
      solution: solution,
    };

    return confirmCommand({ type: 'ExplicitSweep', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { profile, guide1, guide2, position, spline } = params;
    const { type, point, pntDir } = position;
    const { id, leftBound, rightBound } = spline;

    await initEditDependency([profile, guide1, guide2, point, pntDir]);

    setFormData({
      profile: picker.generatePickObjByPickID(profile) as
        | pickedLineData
        | pickedModelData,
      guide1: picker.generatePickObjByPickID(guide1) as pickedLineData,
      guide2: picker.generatePickObjByPickID(guide2) as pickedLineData,
      pntDir: picker.generatePickObjByPickID(pntDir) as
        | pickedLineData
        | pickedFaceData
        | pickedVertexData,
      type,
      point: picker.generatePickObjByPickID(point) as pickedVertexData,
      splineId: picker.generatePickObjByPickID(id) as pickedLineData,
      leftBound: picker.generatePickObjByPickID(leftBound) as pickedVertexData,
      rightBound: picker.generatePickObjByPickID(
        rightBound,
      ) as pickedVertexData,
    });

    setSolution(props?.params?.solution);
  }, [editDxid]);

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  useAsyncEffect(preview, [solution]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-display-explicit-sweep-curve', {
      commandName: 'CreateSurface',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { profile, guide1, guide2, point, pntDir } = formData;

    return (
      profile != null &&
      guide1 != null &&
      guide2 != null &&
      point != null &&
      pntDir != null
    );
  };

  const schema: RJSFSchema = useMemo(() => {
    const { type } = formData;
    return {
      type: 'object',
      properties: {
        profile: {
          type: 'string',
          format: PickInputRJSFFormat.PickSketchCurve,
        },
        guide1: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        guide2: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        type: {
          title: '定位类型',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '两点',
              const: 'twoPoints',
            },
            {
              type: 'string',
              title: '点和方向',
              const: 'pointDirect',
            },
          ],
          default: 'twoPoints',
        },
        point: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertex,
        },
        pntDir: {
          type: 'string',
          format:
            type === 'twoPoints'
              ? PickInputRJSFFormat.PickVertex
              : PickInputRJSFFormat.PickDirection,
        },
        spline: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        leftBound: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertex,
        },
        rightBound: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertex,
        },
        solution: MULTI_SOLUTION_SCHEMA,
      },
    } as RJSFSchema;
  }, [formData.type]);

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onCancel={onClose}
      className='-mt-3'
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        if (v.type !== formData.type) {
          setFormData({
            ...v,
            point: null,
            pntDir: null,
          });
        } else {
          setFormData(v);
        }
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '请输入轮廓',
          'ui:autofocus': true,
        },
        guide1: {
          'ui:placeholder': '请输入引导曲线1',
        },
        guide2: {
          'ui:placeholder': '请输入引导曲线2',
        },
        pntDir: {
          'ui:placeholder':
            formData.type === 'twoPoints' ? '请输入点2' : '请输入方向',
          'ui:options':
            formData.type === 'twoPoints'
              ? ''
              : {
                  label: false,
                  showArrow: true,
                },
        },
        point: {
          'ui:placeholder': '请输入点1',
        },
        spline: {
          'ui:placeholder': '脊线(默认是引导线1)',
        },
        leftBound: {
          'ui:placeholder': '边界1(选填)',
        },
        rightBound: {
          'ui:placeholder': '边界2(选填)',
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      isFormDataValid={isFormDataValid()}
      onSubmit={checkAndFinishDraw}
    />
  );
}
